package com.longshihan.hostapp;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.widget.Toast;

import com.qihoo360.replugin.RePlugin;
import com.qihoo360.replugin.model.PluginInfo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Created by LONGHE001.
 *
 * @time 2019/9/3 0003
 * @des
 * @function
 */

public class InstallPluginUtils {
    private Context context;

    public InstallPluginUtils(Context context) {
        this.context = context;
    }

    public void startRePlugin(String apkPath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo pkgInfo = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        String pluginName = "";
        if (pkgInfo == null || TextUtils.isEmpty(apkPath)) {
            return;
        } else {
            pluginName = pkgInfo.packageName;
        }
        startRePlugin(pluginName, apkPath);
    }

    public void startRePlugin(String pluginName, String apkPath) {
        //插件文件，只有存在就进行安装或者更新
        File file = new File(apkPath);
        String pluginFilePath = context.getFilesDir().getAbsolutePath() + File.separator + file.getName();
        //安装插件过程
        PluginInfo pluginInfo = RePlugin.getPluginInfo(pluginName);//可以从apk里面解出来
        //判断是否已经安装插件
        if (pluginInfo == null) {
            //插件未安装的情况
            if (!file.exists()) {
                Toast.makeText(context, "插件安装失败，插件文件不存在", Toast.LENGTH_SHORT).show();
            } else {
                // 开始复制
                copyAssetsFileToAppFiles(file, file.getName());
                //安装插件
                PluginInfo pluginInfo1 = RePlugin.install(pluginFilePath);
                if (pluginInfo1 == null) {
                    Toast.makeText(context, "插件安装失败，安装出错", Toast.LENGTH_SHORT).show();
                } else {
                    if (listener!=null){
                        listener.onInstallSuccess(pluginInfo1);
                    }
                    Toast.makeText(context, "插件安装成功", Toast.LENGTH_SHORT).show();
                }
            }

        } else {
            //插件已安装,是否需要升级，判断条件是file是否为空
            boolean isInstall = true;
            PackageManager pm1 = context.getPackageManager();
            PackageInfo pkgInfo1 = pm1.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
            if (pkgInfo1 != null) {
                if (pkgInfo1.versionCode <= pluginInfo.getVersion()) {
                    isInstall = false;
                }
            }
            if (file.exists() && isInstall) {
                //判断是否为空，判断是否需要升级
                PluginInfo pluginInfo1 = RePlugin.install(pluginFilePath);
                if (pluginInfo1 != null) {
                    RePlugin.preload(pluginInfo1);
                    if (listener!=null){
                        listener.onInstallSuccess(pluginInfo1);
                    }
                    Toast.makeText(context, "插件升级成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "插件升级失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /**
     * 从assets目录中复制某文件内容
     *
     * @param file        外部地址
     * @param newFileName 复制到/data/data/package_name/files/目录下文件名
     */
    private void copyAssetsFileToAppFiles(File file, String newFileName) {
        InputStream is = null;
        FileOutputStream fos = null;
        int buffsize = 1024;

        try {
            is = new FileInputStream(file);
            fos = context.openFileOutput(newFileName, Context.MODE_PRIVATE);
            int byteCount = 0;
            byte[] buffer = new byte[buffsize];
            while ((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void setListener(onInstallPluginListener listener) {
        this.listener = listener;
    }

    onInstallPluginListener listener;
    public interface onInstallPluginListener {
        void onInstallSuccess(PluginInfo pluginInfo);
    }
}
